Skip to content

Inkling 2 on the HIP backend, with a VRAM expert pool - #129

Open
hun wants to merge 19 commits into
RustingStudio:mainfrom
hun:inkling-port
Open

hun wants to merge 19 commits into
RustingStudio:mainfrom
hun:inkling-port

Conversation

@hun

@hun hun commented Nov 27, 2026

Copy link
Copy Markdown

--backend hip can now run Inkling 2. Inkling 2 Mini is larger than a 16 GB card, so the experts that do not fit run on the CPU. Each layer keeps its most used experts in a VRAM pool, and the pool's placement follows the routing of the text; a decode token is one graph. On an RX 9070 XT (gfx1201, PCIe 3.0, DDR4) with UD-Q4_K_XL this gives about 60 tok/s decode and about 1650 tok/s prefill at 4096 tokens. docs/HIP.md has the measurements for each step.

Start with src/inkling2/forward/pool.rs and the pool paths in forward/device.rs. Changes outside HIP:

  • one-card prompt chunks default to 2048 rows (STRATA_DS_PF_TOKENS);
  • the VRAM pool, slot admission (admit) and the core graph are limited to one GPU, so a --device 0,1 split keeps the current two-card layout;
  • HIP uses the kp16 prefill attention, the tiled controllers and ink_attn_128 by default; --fixed-experts keeps the old kernels.

Verified on gfx1201:

  • --fixed-experts greedy output is byte-identical to Vulkan;
  • the lib tests pass, and the Inkling ctrl and prefill kernel tests now run on HIP and pass;
  • hiprtc compiles kernels.cu for gfx1010, gfx1030, gfx1100, gfx1151 and gfx1201 with the f16 and q8 KV cache.

Not tested: CUDA (no NVIDIA card here), two GPUs, and RDNA1-3.5 hardware. #125 changes the signature of proj_n; whichever lands second adds the argument to the pool's router call in prefill_ffn_pool.

@aletheore

aletheore Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Aletheore Flash Lite review

What this PR does. The PR caches each HIP device's PCI bus address when the GPU is created and changes the sysfs free-VRAM lookup to match by that address first, falling back to matching by VRAM size when no card has it. This affects the HIP backend's reported free memory on AMD GPUs, so budgets account for VRAM used by the desktop and other graphics clients on the correct card. The title mentions Inkling 2 and a VRAM expert pool, but the diff contains neither, only the PCI-address and fallback changes.

Merge confidence Review effort Merge risk
2 / 5 1 / 5 Medium
Area Files Lines
src/hip 1 +23 −17

4 finding(s) posted as inline review comment(s). 7 earlier finding(s) from previous pushes still open. 3 earlier finding(s) no longer detected in this push.

# Severity Category Where
1 🟠 High Correctness mod.rs:574 When an address is given but matches no card, drm_free falls back to a VRAM-size match that can pick the…
2 🟠 High Correctness mod.rs:573 at_bus lowercases the sysfs name but compares it against the runtime address without lowercasing it. If the…
3 🔵 Low Performance mod.rs:574 drm_free scans /sys/class/drm twice on every call that finds no address match, and always when the address is…
4 🔵 Low Maintainability mod.rs:1408 The new test assumes the sibling PCI address is absent and that the size match returns the same card, with no…
- 🟠 High Correctness pool.rs:83 Earlier finding, still open
- 🟠 High Correctness mod.rs:462 Earlier finding, still open
- 🟠 High Correctness mod.rs:606 Earlier finding, still open
- 🔵 Low Performance mat.rs:352 Earlier finding, still open
- 🔵 Low Performance device.rs:1625 Earlier finding, still open
- 🔵 Low Performance ffi.rs:204 Earlier finding, still open
- 🔵 Low Maintainability mod.rs:1401 Earlier finding, still open
Review details

Reviewed 1 file(s); skipped 0. Dismissed 0; outside PR diff 0. Grounding: 4 of 4 proposed finding(s).

Fix all with your agent
File: src/hip/mod.rs
Line: 574
Issue: When an address is given but matches no card, drm_free falls back to a VRAM-size match that can pick the other card of equal size. On a two-card system with identical VRAM sizes, the runtime reports a PCI address that the sysfs canonical name does not match (for example a case or format difference). The old code returned None and never read the other card. The new code falls through to the size match, which returns the other card's free VRAM. The VRAM budget is then computed from the wrong card and can over-commit the card the device runs on.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/hip/mod.rs
Line: 573
Symbol: drm_free
Issue: at_bus lowercases the sysfs name but compares it against the runtime address without lowercasing it. If the HIP runtime returns the bus ID with uppercase hex digits (for example '0000:0C:00.0'), the sysfs name is lowercased and never equals it. at_bus never matches, so every call takes the size fallback, which the change above makes silent. The address path becomes dead code for that runtime.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/hip/mod.rs
Line: 574
Issue: drm_free scans /sys/class/drm twice on every call that finds no address match, and always when the address is absent. mem_info runs when the budget is queried. With no runtime address, or an address no card has, the first pass reads every drm entry and finds nothing, then the second pass repeats the same reads with the size predicate. Each budget query pays for two directory scans and roughly double the file reads. One pass with a combined predicate would avoid this.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/hip/mod.rs
Line: 1408
Symbol: hiprtc_compiles_the_kernels
Issue: The new test assumes the sibling PCI address is absent and that the size match returns the same card, with no check of which card matched. On a machine with another amdgpu card of the same VRAM size, or if the sibling function address exists, the assertion can pass using a different card's free VRAM within the 256 MiB tolerance. The test then does not verify that the size fallback selects the device's own card.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

The pull request description says: "Not tested: CUDA (no NVIDIA card here), two GPUs, and RDNA1-3.5 hardware.". This review read the diff only: it did not compile or run the code, so it cannot confirm that part works.

Blast radius: 53 other file(s) depend on what this PR changes (3 directly, 50 indirectly)

Computed from the import graph of this exact commit, not guessed by a model. It sees imports only, so dynamic imports, reflection and non-code references are not counted.

  • src/hip/mod.rs is imported by src/backend.rs, src/lib.rs, tests/common/mod.rs

Indirectly affected: src/calibrate.rs, src/cpu_worker.rs, src/cuda/mod.rs, src/deepseek/chat.rs, src/deepseek/mat.rs, src/expert_cache.rs (+44 more)

The graph is large; this list is capped and not exhaustive.

@aletheore

aletheore Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

🔍 Aletheore evidence diff

graph LR
    n0["src/backend.rs"]
    n1["cpu_worker.rs"]
    n2["src/cuda/mod.rs"]
    n3["mat.rs"]
    n4["src/hip/mod.rs"]
    n5["src/inkling2/forward.rs"]
    n6["tests/common/mod.rs"]
    n7["src/deepseek/forward.rs"]
    n8["src/deepseek/mod.rs"]
    n9["expert_cache.rs"]
    n10["src/gemma4/forward.rs"]
    n11["src/glm/forward.rs"]
    n12["src/gpu_model.rs"]
    n13["prefill.rs"]
    n14["src/hy4/forward.rs"]
    n15["chat.rs"]
    n16["dspark.rs"]
    n17["src/inkling2/mod.rs"]
    n18["src/kolibri/forward.rs"]
    n19["lib.rs"]
    n20["main.rs"]
    n21["src/model.rs"]
    n22["dflash.rs"]
    n23["src/raon/forward.rs"]
    n24["projector.rs"]
    n25["src/vulkan/mod.rs"]
    n26["preflight.rs"]
    n27["tests/backend.rs"]
    n28["cpu_moe.rs"]
    n29["gguf.rs"]
    n30["tests/gpu_model.rs"]
    n31["inkling2_forward.rs"]
    n32["kernels.rs"]
    n33["kv_q8.rs"]
    n34["kv_turbo.rs"]
    n35["llama_numerics.rs"]
    n36["tests/model.rs"]
    n37["quant.rs"]
    n38["tokenizer.rs"]
    n39["vision.rs"]
    n40["vision_gpu.rs"]
    n41["vulkan_split_kv.rs"]
    n0 --> n9
    n0 --> n12
    n0 --> n13
    n0 --> n16
    n0 --> n19
    n0 --> n20
    n0 --> n21
    n0 --> n24
    n0 --> n25
    n0 --> n27
    n0 --> n30
    n0 --> n32
    n0 --> n33
    n0 --> n34
    n0 --> n35
    n0 --> n40
    n0 --> n41
    n1 --> n12
    n1 --> n13
    n1 --> n19
    n1 --> n20
    n1 --> n25
    n1 --> n32
    n2 --> n19
    n2 --> n25
    n2 --> n26
    n2 --> n30
    n2 --> n33
    n2 --> n34
    n2 --> n35
    n2 --> n41
    n3 --> n7
    n3 --> n8
    n3 --> n10
    n3 --> n11
    n3 --> n14
    n3 --> n16
    n3 --> n18
    n3 --> n20
    n3 --> n22
    n3 --> n23
    n3 --> n37
    n4 --> n19
    n5 --> n15
    n5 --> n16
    n5 --> n17
    n5 --> n18
    n5 --> n20
    n5 --> n39
    n6 --> n27
    n6 --> n28
    n6 --> n29
    n6 --> n30
    n6 --> n31
    n6 --> n32
    n6 --> n33
    n6 --> n34
    n6 --> n35
    n6 --> n36
    n6 --> n37
    n6 --> n38
    n6 --> n39
    n6 --> n41
    classDef changed fill:#d9772c,color:#fff,stroke:#b85f1c;
    classDef changedFinding fill:#c0392b,color:#fff,stroke:#922b21;
    classDef dependent fill:#f2f0ec,color:#18140f,stroke:#d6d0c5;
    class n0 changed
    class n1 changed
    class n2 changed
    class n3 changed
    class n4 changed
    class n5 changed
    class n6 changed
    class n7 dependent
    class n8 dependent
    class n9 dependent
    class n10 dependent
    class n11 dependent
    class n12 dependent
    class n13 dependent
    class n14 dependent
    class n15 dependent
    class n16 dependent
    class n17 dependent
    class n18 dependent
    class n19 dependent
    class n20 dependent
    class n21 dependent
    class n22 dependent
    class n23 dependent
    class n24 dependent
    class n25 dependent
    class n26 dependent
    class n27 dependent
    class n28 dependent
    class n29 dependent
    class n30 dependent
    class n31 dependent
    class n32 dependent
    class n33 dependent
    class n34 dependent
    class n35 dependent
    class n36 dependent
    class n37 dependent
    class n38 dependent
    class n39 dependent
    class n40 dependent
    class n41 dependent
Loading

What changed
Deterministic, computed from this commit's real scan and import graph - posted on every run, whether or not Flash Review found anything.

  • docs/HIP.md · modified · +97/-0
  • docs/USAGE.md · modified · +1/-1
  • src/backend.rs · modified · +23/-0 · +9 functions · 17 other dependents
  • src/cpu_worker.rs · modified · +1/-1 · 6 other dependents
  • src/cuda/kernels.cu · modified · +53/-0
  • src/cuda/mod.rs · modified · +22/-11 · +3 functions · 8 other dependents
  • src/deepseek/mat.rs · modified · +86/-3 · +4 functions · 11 other dependents
  • src/hip/ffi.rs · modified · +16/-0 · +1 function
  • src/hip/mod.rs · modified · +323/-30 · +34 functions · 1 other dependent
  • src/inkling2/forward.rs · modified · +83/-9 · +2 functions · 6 other dependents
  • src/inkling2/forward/device.rs · modified · +320/-22 · +5 functions
  • src/inkling2/forward/pool.rs · +274/-0 · new file, 15 symbols
  • src/inkling2/forward/worker.rs · +112/-0 · new file, 8 symbols
  • tests/common/mod.rs · modified · +11/-1 · 14 other dependents
  • tests/inkling2_ctrl.rs · modified · +1/-1
  • tests/inkling2_prefill.rs · modified · +3/-3

Aggregate deltas

  • Modules: +2
  • Dependency graph edges: +13
  • Commits: 15

@hun
hun marked this pull request as ready for review November 27, 2026 09:58
let bias = d.alloc_slab_on(0, &bytes(&ml.bias), None, b_res, f_res)?;
let sc = |v: &[f32], d: &mut dev::Dev| if v.is_empty() { Some(None) } else { d.alloc_slab_on(0, &bytes(v), None, b_res, f_res).map(Some) };
let (gu_scale, dn_scale) = (sc(&ml.gu_scale, d)?, sc(&ml.down_scale, d)?);
let be = &*d.parts[0].be;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 1 of 8

Pool::new keeps a PoolLayer for every layer even when its layout's slot buffer failed to allocate, leaving base 0 and an all -1 table. Two layouts (e.g. NVFP4 and Q8_0) share the budget and the second alloc_room returns None. slots.iter().all(buf none) is false, so the pool is kept. Those layers get layer(ip) Some, so all_full and layer_ffn_pool treat them as pooled. Decode then calls moe_gemv with base 0 and slot -1 (or misses that were never staged), reading invalid device memory. has_room checks exist only in the prefill path.

Prompt for your AI agent
File: src/inkling2/forward/pool.rs
Line: 83
Symbol: new
Issue: Pool::new keeps a PoolLayer for every layer even when its layout's slot buffer failed to allocate, leaving base 0 and an all -1 table. Two layouts (e.g. NVFP4 and Q8_0) share the budget and the second `alloc_room` returns None. `slots.iter().all(buf none)` is false, so the pool is kept. Those layers get `layer(ip)` Some, so `all_full` and `layer_ffn_pool` treat them as pooled. Decode then calls `moe_gemv` with base 0 and slot -1 (or misses that were never staged), reading invalid device memory. `has_room` checks exist only in the prefill path.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A layout whose slot buffer fails to allocate gets no slots, so its table stays all -1. moe_gemv skips slot ids below 0 (kernels.cu, if (e < 0) return), and ink_slots sends every one of those experts to the CPU worker. The layer is slow, but it reads no invalid memory. Prefill checks has_room and uses the host path there.

Comment thread src/hip/mod.rs
None | Some("auto") => default,
Some("0") => false,
Some(_) => true,
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 2 of 8

HIP auto now enables the fast Inkling 2 kernels on one card, contrary to the InkFlags comment that one card keeps the main kernels. ink_flags_from is called with multi=false, but fast defaults to true unless --fixed-experts is set. A default single-GPU run switches to ink_attn_128, kp16 and the tiled ctrl pair, changing greedy text. The docs only mention placement and do not say the kernels changed, and --fixed-experts is documented as the bit-identical path.

Prompt for your AI agent
File: src/hip/mod.rs
Line: 462
Symbol: ink_flags_from
Issue: HIP `auto` now enables the fast Inkling 2 kernels on one card, contrary to the InkFlags comment that one card keeps the main kernels. `ink_flags_from` is called with multi=false, but `fast` defaults to true unless `--fixed-experts` is set. A default single-GPU run switches to ink_attn_128, kp16 and the tiled ctrl pair, changing greedy text. The docs only mention placement and do not say the kernels changed, and `--fixed-experts` is documented as the bit-identical path.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is intended: HIP is an opt-in backend, and the faster kernels make a 4096-token prompt about 1.7x faster. --fixed-experts keeps the older kernels and stays bit-identical to Vulkan. docs/HIP.md now says so (41e6270), and STRATA_DS_FAST_KERNELS=0 switches them off.

Comment thread src/hip/mod.rs
self.hip.check(last, "hipHostRegister").map(|_| false)
}
fn side_mark(&self) -> anyhow::Result<usize> { self.mark(self.side) }
fn main_waits(&self, m: usize) -> anyhow::Result<()> { self.wait_mark(self.stream, m) }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 3 of 8

pin_host registers page-rounded ranges, so adjacent matrices sharing a boundary page make hipHostRegister fail; the caller then stops pinning silently. The gate_up and down matrices of one expert share their boundary page. The second registration fails with already-registered and returns Ok(false), or Err, which Pool::new reports and then breaks out of the loop. The staging copies quietly stay on the pinned ring and the claimed DMA speed-up does not happen. The containment check only covers ranges fully inside one earlier range.

Prompt for your AI agent
File: src/hip/mod.rs
Line: 606
Symbol: main_waits
Issue: pin_host registers page-rounded ranges, so adjacent matrices sharing a boundary page make hipHostRegister fail; the caller then stops pinning silently. The gate_up and down matrices of one expert share their boundary page. The second registration fails with already-registered and returns Ok(false), or Err, which Pool::new reports and then breaks out of the loop. The staging copies quietly stay on the pinned ring and the claimed DMA speed-up does not happen. The containment check only covers ranges fully inside one earlier range.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On ROCm 7.2.3 two hipHostRegister calls whose ranges share a page both succeed (checked with a two-range test on a read-only file mapping), so the second registration does not fail here. STRATA_INK_PIN is opt-in, and if a registration fails it prints a message and the copies go through the pinned ring. I have left this as it is.

Comment thread src/deepseek/mat.rs
self.reclaim();
let mut best: Option<(usize, f32)> = None;
for (i, c) in cands.iter().enumerate() {
let n = self.seen.entry(c[0].0.as_ptr() as usize).or_insert(0.0);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low · Performance · 5 of 8

admit scans every resident entry for each candidate matrix and calls reclaim on every miss, every layer, every token. On each token, each layer with misses runs victim over all of exs (hundreds to thousands of entries, each with a tensor lookup) for up to two matrices, plus reclaim. This adds host work on the decode critical path for every layer even when nothing is admitted; keeping an ordered index of coldest slots per shape would avoid it.

Prompt for your AI agent
File: src/deepseek/mat.rs
Line: 352
Symbol: admit
Issue: admit scans every resident entry for each candidate matrix and calls reclaim on every miss, every layer, every token. On each token, each layer with misses runs `victim` over all of `exs` (hundreds to thousands of entries, each with a tensor lookup) for up to two matrices, plus `reclaim`. This adds host work on the decode critical path for every layer even when nothing is admitted; keeping an ordered index of coldest slots per shape would avoid it.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

admit runs only on the hybrid (slab) path. On HIP the expert pool replaces that path by default. An index of the coldest slots per shape is a reasonable follow-up.

Comment thread src/hip/mod.rs Outdated
let t = read(dev.join("mem_info_vram_total"))?;
if t.abs_diff(total) > 256 << 20 { return None }
Some(t.saturating_sub(read(dev.join("mem_info_vram_used"))?))
})

@aletheore aletheore Bot Nov 27, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No longer detected as of f35549936812.


🟡 Medium · Correctness · 6 of 8

drm_free matches any amdgpu card whose VRAM total is within 256 MiB, so with two identical cards it can read the wrong card's usage. On a system with two same-size cards, find_map returns the first card in /sys/class/drm that matches the total. The budget then uses that card's used VRAM rather than the device in use, so the free figure is wrong and the budget can be too large or too small.

Prompt for your AI agent
File: src/hip/mod.rs
Line: 566
Symbol: drm_free
Issue: drm_free matches any amdgpu card whose VRAM total is within 256 MiB, so with two identical cards it can read the wrong card's usage. On a system with two same-size cards, `find_map` returns the first card in /sys/class/drm that matches the total. The budget then uses that card's used VRAM rather than the device in use, so the free figure is wrong and the budget can be too large or too small.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 49211c8: the card is found by the device's PCI address (hipDeviceGetPCIBusId), and the VRAM-size match is kept only as a fallback. A test checks that the lookup finds the device's card.

/// The routed experts of a prompt chunk in a pool layer: the pool's slots, and the chunk's other experts copied
/// into the staging slots in rounds of `pool::STAGE`, with a wait before each refill. The experts run in the
/// order of their rounds, so a round's rows are one block. False: a small batch with more misses than staging
/// slots, left to the host path (`p.hn` holds the normed input).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low · Performance · 7 of 8

prefill_ffn_pool's non-GEMM path runs routing and the id read (a host sync) before it knows it can take the layer, then returns false. A small batch with more than STAGE missing experts sends the layer to Ok(false) after queuing rms_norm, route and a synchronous be.get of the ids. The host path then recomputes the routing, so every such layer pays a PCIe round trip and duplicate work per chunk.

Prompt for your AI agent
File: src/inkling2/forward/device.rs
Line: 1625
Issue: prefill_ffn_pool's non-GEMM path runs routing and the id read (a host sync) before it knows it can take the layer, then returns false. A small batch with more than STAGE missing experts sends the layer to `Ok(false)` after queuing rms_norm, route and a synchronous `be.get` of the ids. The host path then recomputes the routing, so every such layer pays a PCIe round trip and duplicate work per chunk.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. This is part of why draft verification is slow on HIP, which needs more work than this check. It is left for a follow-up.

Comment thread tests/common/mod.rs Outdated
if wanted("hip") {
match rusting_strata::hip::Gpu::new(0) {
Ok(g) => v.push(("hip", Box::new(g))),
Err(e) if format!("{e}") == "HIP init" => eprintln!("SKIP: hip: {e:#}"),

@aletheore aletheore Bot Nov 27, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No longer detected as of 41e6270887bc.


🔵 Low · Maintainability · 8 of 8

The HIP skip branch matches the error by exact display string, which is brittle. The format!("{e}") == "HIP init" check only matches when the error display is exactly that text. Any added context or wording change turns a missing-GPU skip into a test panic on machines without HIP.

Prompt for your AI agent
File: tests/common/mod.rs
Line: 71
Symbol: backends
Issue: The HIP skip branch matches the error by exact display string, which is brittle. The `format!("{e}") == "HIP init"` check only matches when the error display is exactly that text. Any added context or wording change turns a missing-GPU skip into a test panic on machines without HIP.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 50dabe9: the test skips when any error in the chain is "HIP init", so a missing hiprtc also skips the tests.

@hun
hun marked this pull request as draft November 27, 2026 10:04
@hun
hun marked this pull request as ready for review November 27, 2026 10:04
Comment thread src/hip/mod.rs Outdated
Some(b) => std::fs::canonicalize(&dev).ok()?.file_name()?.to_string_lossy().to_lowercase() == b,
None => t.abs_diff(total) <= 256 << 20,
};
if !ours { return None }

@aletheore aletheore Bot Nov 27, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No longer detected as of f35549936812.


🟠 High · Correctness · 1 of 4

When the PCI address is known but matches no sysfs card, drm_free returns None, so the desktop's VRAM is ignored entirely. If hipDeviceGetPCIBusId returns an address that does not match the canonical sysfs name, or canonicalize fails, ours is false and drm_free returns None. mem_info then falls back to usize::MAX and the pool budget is taken from hipMemGetInfo alone. The pool can then fill VRAM the compositor needs, and the framebuffer pin fails. The old size-based match would still have found the card.

Prompt for your AI agent
File: src/hip/mod.rs
Line: 570
Symbol: host_mailbox
Issue: When the PCI address is known but matches no sysfs card, drm_free returns None, so the desktop's VRAM is ignored entirely. If hipDeviceGetPCIBusId returns an address that does not match the canonical sysfs name, or canonicalize fails, `ours` is false and drm_free returns None. mem_info then falls back to usize::MAX and the pool budget is taken from hipMemGetInfo alone. The pool can then fill VRAM the compositor needs, and the framebuffer pin fails. The old size-based match would still have found the card.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f355499: when no card has the PCI address (or the runtime gives none), the lookup falls back to the VRAM-size match. The test now also checks that an address no card has still finds the card through its size.

Comment thread src/hip/ffi.rs

/// The device's PCI address as sysfs names it ("0000:0c:00.0"), or None when the runtime does not give it.
pub fn pci_bus_id(&self, device: c_int) -> Option<String> {
let f: unsafe extern "C" fn(*mut c_char, c_int, c_int) -> c_int = unsafe { Self::sym(&self._lib, "hipDeviceGetPCIBusId") }?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low · Performance · 2 of 4

pci_bus_id re-resolves the hipDeviceGetPCIBusId symbol on every call, and it runs on every mem_info query. mem_info is called often during pool sizing and admission. Each call does a dynamic symbol lookup plus a HIP runtime call, and drm_free then does canonicalize and sysfs reads. The bus id is fixed per device, so this is repeated work that could be resolved once in Gpu::new and stored.

Prompt for your AI agent
File: src/hip/ffi.rs
Line: 204
Symbol: attribute
Issue: pci_bus_id re-resolves the hipDeviceGetPCIBusId symbol on every call, and it runs on every mem_info query. mem_info is called often during pool sizing and admission. Each call does a dynamic symbol lookup plus a HIP runtime call, and drm_free then does canonicalize and sysfs reads. The bus id is fixed per device, so this is repeated work that could be resolved once in Gpu::new and stored.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f355499: the address is read once when the device opens and kept on the Gpu.

Comment thread src/hip/mod.rs Outdated
let (mut free, mut total) = (0usize, 0usize);
self.hip.check(unsafe { (self.hip.mem_get_info)(&mut free, &mut total) }, "hipMemGetInfo")?;
Ok((free, total))
Ok((free.min(drm_free(total, self.hip.pci_bus_id(self.device as i32).as_deref()).unwrap_or(usize::MAX)), total))

@aletheore aletheore Bot Nov 27, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No longer detected as of f35549936812.


🔵 Low · Performance · 3 of 4

mem_info now does a HIP call, a sysfs canonicalize and several file reads on each query, which the old code did only once per size match. Each mem_info call now runs hipDeviceGetPCIBusId, fs::canonicalize and reads of mem_info_vram_total and mem_info_vram_used. If the budget is polled while the pool admits slots, this adds syscalls to a path that used to be a single HIP query. Caching the card's sysfs path at construction would remove this.

Prompt for your AI agent
File: src/hip/mod.rs
Line: 640
Issue: mem_info now does a HIP call, a sysfs canonicalize and several file reads on each query, which the old code did only once per size match. Each mem_info call now runs hipDeviceGetPCIBusId, fs::canonicalize and reads of mem_info_vram_total and mem_info_vram_used. If the budget is polled while the pool admits slots, this adds syscalls to a path that used to be a single HIP query. Caching the card's sysfs path at construction would remove this.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f355499 together with the previous one: mem_info no longer calls the runtime for the address. It still reads sysfs, as before this change; VRAM is queried at load and pool sizing, not per token.

Comment thread src/hip/mod.rs
let (mut free, mut total) = (0usize, 0usize);
g.hip.check(unsafe { (g.hip.mem_get_info)(&mut free, &mut total) }, "hipMemGetInfo").unwrap();
let drm = drm_free(total, Some(&bus)).unwrap_or_else(|| panic!("no amdgpu card at {bus} in /sys/class/drm"));
eprintln!("{bus}: {:.2} GB free by the driver, {:.2} GB by HIP", drm as f64 / 1e9, free as f64 / 1e9);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low · Maintainability · 4 of 4

The negative test uses a hard-coded PCI address that may exist on some machines. On a machine that really has a card at 0000:ff:1f.7, the assertion that no card matches fails, even though drm_free is correct. The test should derive a non-existent address from the real one, for example by changing the function field.

Prompt for your AI agent
File: src/hip/mod.rs
Line: 1401
Issue: The negative test uses a hard-coded PCI address that may exist on some machines. On a machine that really has a card at 0000:ff:1f.7, the assertion that no card matches fails, even though drm_free is correct. The test should derive a non-existent address from the real one, for example by changing the function field.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f355499: the test derives the absent address from the device's own by changing its PCI function.

…ress

The address is read once when the device opens, not on every VRAM query.
Comment thread src/hip/mod.rs
});
let at_bus = |dev: &std::path::Path, _| bus.is_some_and(|b| std::fs::canonicalize(dev).ok()
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_lowercase())).is_some_and(|n| n == b));
free_where(&at_bus).or_else(|| free_where(&|_, t: usize| t.abs_diff(total) <= 256 << 20))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 1 of 4

When an address is given but matches no card, drm_free falls back to a VRAM-size match that can pick the other card of equal size. On a two-card system with identical VRAM sizes, the runtime reports a PCI address that the sysfs canonical name does not match (for example a case or format difference). The old code returned None and never read the other card. The new code falls through to the size match, which returns the other card's free VRAM. The VRAM budget is then computed from the wrong card and can over-commit the card the device runs on.

Prompt for your AI agent
File: src/hip/mod.rs
Line: 574
Issue: When an address is given but matches no card, drm_free falls back to a VRAM-size match that can pick the other card of equal size. On a two-card system with identical VRAM sizes, the runtime reports a PCI address that the sysfs canonical name does not match (for example a case or format difference). The old code returned None and never read the other card. The new code falls through to the size match, which returns the other card's free VRAM. The VRAM budget is then computed from the wrong card and can over-commit the card the device runs on.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the trade-off the previous review asked for (thread above): the size match runs only when no card in /sys/class/drm has the device's address. That is the behaviour before this PR, and the doc comment on drm_free says it may pick the other card when two cards have the same size. Returning None there instead would leave the desktop's VRAM uncounted, which is the failure the fallback exists for.

Comment thread src/hip/mod.rs
Some(t.saturating_sub(read(dev.join("mem_info_vram_used"))?))
});
let at_bus = |dev: &std::path::Path, _| bus.is_some_and(|b| std::fs::canonicalize(dev).ok()
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_lowercase())).is_some_and(|n| n == b));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 2 of 4

at_bus lowercases the sysfs name but compares it against the runtime address without lowercasing it. If the HIP runtime returns the bus ID with uppercase hex digits (for example '0000:0C:00.0'), the sysfs name is lowercased and never equals it. at_bus never matches, so every call takes the size fallback, which the change above makes silent. The address path becomes dead code for that runtime.

Prompt for your AI agent
File: src/hip/mod.rs
Line: 573
Symbol: drm_free
Issue: at_bus lowercases the sysfs name but compares it against the runtime address without lowercasing it. If the HIP runtime returns the bus ID with uppercase hex digits (for example '0000:0C:00.0'), the sysfs name is lowercased and never equals it. at_bus never matches, so every call takes the size fallback, which the change above makes silent. The address path becomes dead code for that runtime.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The address is lowercased where it is read: Hip::pci_bus_id in src/hip/ffi.rs returns to_lowercase() of the runtime's string, so both sides of the comparison are lowercase.

Comment thread src/hip/mod.rs
});
let at_bus = |dev: &std::path::Path, _| bus.is_some_and(|b| std::fs::canonicalize(dev).ok()
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_lowercase())).is_some_and(|n| n == b));
free_where(&at_bus).or_else(|| free_where(&|_, t: usize| t.abs_diff(total) <= 256 << 20))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low · Performance · 3 of 4

drm_free scans /sys/class/drm twice on every call that finds no address match, and always when the address is absent. mem_info runs when the budget is queried. With no runtime address, or an address no card has, the first pass reads every drm entry and finds nothing, then the second pass repeats the same reads with the size predicate. Each budget query pays for two directory scans and roughly double the file reads. One pass with a combined predicate would avoid this.

Prompt for your AI agent
File: src/hip/mod.rs
Line: 574
Issue: drm_free scans /sys/class/drm twice on every call that finds no address match, and always when the address is absent. mem_info runs when the budget is queried. With no runtime address, or an address no card has, the first pass reads every drm entry and finds nothing, then the second pass repeats the same reads with the size predicate. Each budget query pays for two directory scans and roughly double the file reads. One pass with a combined predicate would avoid this.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The second scan runs only when no card has the address. mem_info runs at load and while the pool is sized, not per token, so the extra directory read does not matter here.

Comment thread src/hip/mod.rs
assert!(drm <= total);
// The same card in another PCI function, which no card has: the size match finds the card.
let other = format!("{}{}", &bus[..bus.len() - 1], if bus.ends_with('7') { '6' } else { '7' });
let by_size = drm_free(total, Some(&other)).expect("the VRAM size finds the card when no card has the address");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low · Maintainability · 4 of 4

The new test assumes the sibling PCI address is absent and that the size match returns the same card, with no check of which card matched. On a machine with another amdgpu card of the same VRAM size, or if the sibling function address exists, the assertion can pass using a different card's free VRAM within the 256 MiB tolerance. The test then does not verify that the size fallback selects the device's own card.

Prompt for your AI agent
File: src/hip/mod.rs
Line: 1408
Symbol: hiprtc_compiles_the_kernels
Issue: The new test assumes the sibling PCI address is absent and that the size match returns the same card, with no check of which card matched. On a machine with another amdgpu card of the same VRAM size, or if the sibling function address exists, the assertion can pass using a different card's free VRAM within the 256 MiB tolerance. The test then does not verify that the size fallback selects the device's own card.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, the test cannot tell two cards of the same size apart. It checks the address match on the device's card and that the fallback returns a card's figure; a machine with two equal cards would need a check by sysfs path, which this machine cannot run.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant